<template>
    <div class="app-container">
        <el-form :model="postForm" :rules="rules" ref="informationForm" label-width="100px" style="width: 80%;">
            <el-form-item label="课程名称" v-if="courseName">
                <el-input v-model="courseName" :disabled="true"></el-input>
            </el-form-item>
        </el-form>
        <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row row-key="$index">

            <el-table-column align="left" label='音频列表' class="padding-top:10px;">
                <template scope="scope">
                    <el-form :inline="true" :model="scope.row" class="demo-form-inline" :ref="'postForm' + scope.$index ">
                        <el-form-item label="音频名称" prop="name">
                            <el-input v-model="scope.row.name" placeholder="音频名称" style="width: 300px;"></el-input>
                        </el-form-item>
                        <el-form-item label="排序" prop="serial">
                            <el-input v-model="scope.row.serial" placeholder="排序" style="width: 50px;"></el-input>
                        </el-form-item>
                        <el-form-item label="" prop="orgAudioUrl">
                            <el-upload
                                    class="upload-demo"
                                    :action="actionUrl"
                                    :with-credentials="true"
                                    :show-file-list="true"
                                    accept="audio/*"
                                    :on-success="scope.row.uploadSuccess"
                                    :on-error="handleError"
                                    :before-upload="beforeUpload"
                            >
                                <el-button size="small" type="primary">点击上传</el-button>
                                <div class="el-upload__tip" slot="tip" v-if="!isUploading">只能上传mp3/m4a文件，文件最大50MB</div>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="免费试听" prop="free">
                            <el-switch
                                    v-model="scope.row.free"
                                    on-color="#13ce66"
                                    off-color="#ff4949"
                                    :on-value="1"
                                    :off-value="0">
                            </el-switch>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit(scope.row, 'postForm' + scope.$index )" v-if="scope.row.id">更新</el-button>
                            <el-button type="primary" @click="onSubmit(scope.row, 'postForm' + scope.$index )" v-if="!scope.row.id">保存</el-button>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
        </el-table>
        <p/>
        <el-button style="margin-left: 20px;" @click="newForm" type="primary" icon="edit">新增</el-button>
    </div>
</template>

<script>

    import { add, update, getList } from '@/api/audio';
    import { getDetail as getCourseDetail } from '@/api/course';

    export default {
        data() {
            return {
                loading: false,
                actionUrl: process.env.BASE_API + '/common/upload/audio',
                isUploading: false,
                postForm: {
                    id: '',
                    name: '',
                    courseId: '',
                    orgAudioUrl: '',
                    free: 0,
                    status: 1,
                    serial: 1
                },
                listQuery: {
                        page: 1,
                        pageSize: 100,
                        searchCourseId: '',
                        orderKey: 'AUDIO_SERIAL_ASC'
                },
                list: null,
                total: null,
                rules: {
                    name: [
                        { required: true, message: '音频名称', trigger: 'blur' },
                        { min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
                    ],
                    orgAudioUrl: [
                        { required: true, message: '请输入上传音频文件', trigger: 'blur' }
                    ],
                    serial: [
                        { type: 'integer', required: true, message: '请输入序号', min: 1, trigger: 'blur' }
                    ]
                },
                courseName: ''
            }
        },
        created() {
            const reg = /\/batch\/(\d*)$/
            if (reg.test(this.$route.path)) {
                const ID = RegExp.$1;
                this.postForm.courseId = ID;
                this.listQuery.searchCourseId = ID;
                this.getCourseInfo();
            }
            this.getList();
        },
        methods: {
            getList() {
                this.listLoading = true;
                getList(this.listQuery).then(response => {
                    this.list = response.data.data;
                    this.total = response.data.totalCount;
                    this.listLoading = false;
                    const len = this.list.length;
                    for (let i = 0; i < len; i++) {
                        const item = this.list[i];
                        item.uploadSuccess = (function(item) {
                            return function(response) {
                                if (response.code === 0) {
                                    item.orgAudioUrl = response.data;
                                }
                            }
                        })(item);
                    }
                }).catch(err => {
                    console.log(err);
                    this.listLoading = false;
                });
            },
            getCourseInfo() {
                const courseID = this.postForm.courseId;
                if (!courseID) {
                    return;
                }
                getCourseDetail(courseID).then(response => {
                    this.courseName = response.data.name;
                }).catch(err => {
                    console.log(err)
                });
            },
            beforeUpload(file) {
                const reg = /(.mp3|.m4a)$/
                const fileOK = reg.test(file.name);
                return fileOK;
            },
            handleError(error) {
                this.$message({
                    title: '上传失败',
                    message: error,
                    type: 'error',
                    duration: 2000
                });
            },
            onSubmit(item, formRef) {
                const that = this;
                this.$refs[formRef].validate(valid => {
                    console.log('valid=' + valid);
                    if (valid) {
                        this.loading = true;
                        if (item.id) {
                            update(item).then(response => {
                                if (response.code === 0) {
                                    that.$notify({
                                        title: '成功',
                                        message: '更新成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                } else {
                                    that.$message({
                                        title: '失败',
                                        message: '原因:' + response.msg,
                                        type: 'error',
                                        duration: 3000
                                    });
                                }
                                that.loading = false;
                            }).catch(err => {
                                that.$message({
                                    title: '失败',
                                    message: '原因:' + err.msg ? err.msg : err,
                                    type: 'error',
                                    duration: 3000
                                });
                                that.loading = false;
                            });
                        } else {
                            add(item).then(response => {
                                if (response.code === 0) {
                                    that.$notify({
                                        title: '成功',
                                        message: '添加成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                    item.id = parseInt(response.data);
                                } else {
                                    that.$message({
                                        title: '失败',
                                        message: '原因:' + response.msg,
                                        type: 'error',
                                        duration: 3000
                                    });
                                }
                                that.loading = false;
                            }).catch(err => {
                                that.$message({
                                    title: '失败',
                                    message: '原因:' + err.msg ? err.msg : err,
                                    type: 'error',
                                    duration: 3000
                                });
                                that.loading = false;
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            goBack() {
                this.$router.go(-1);
            },
            newForm() {
                if (this.list == null) {
                    this.list = [];
                }
                const item = {
                    id: '',
                    name: '',
                    courseId: this.postForm.courseId,
                    orgAudioUrl: '',
                    free: 0,
                    status: 0,
                    serial: this.list.length + 1
                }
                item.uploadSuccess = (function(item) {
                    return function(response) {
                        if (response.code === 0) {
                            item.orgAudioUrl = response.data;
                        }
                    }
                })(item);
                this.list.push(item);
            }
        }
    }
</script>